package com.yinuo.controller;

import com.alibaba.fastjson.JSON;
import com.yinuo.common.DateUtil;
import com.yinuo.common.UUIDUtil;
import com.yinuo.entity.DocBinary;
import com.yinuo.entity.GlobalContext;
import com.yinuo.entity.LinuxShellCmd;
import com.yinuo.common.JsonResult;
import com.yinuo.entity.PageJson;
import com.yinuo.repository.DocRepository;
import com.yinuo.repository.LinuxRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.persistence.criteria.*;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.util.*;

/**
 * Created by Administrator on 2018/7/16.
 */
@Controller
@RequestMapping("linux")
public class LinuxController {
    private static Logger logger = LoggerFactory.getLogger(LinuxController.class);

    @Autowired
    private LinuxRepository linuxRepository;
    @Autowired
    private DocRepository linuxDocRepository;

    @RequestMapping("linuxCmdAdd")
    @ResponseBody
    public String toAddCmd(LinuxShellCmd lsc){
        LinuxShellCmd linuxShellCmd = linuxRepository.findByKey(lsc.getKey());
        boolean exists = linuxShellCmd==null?false:true;
        if(exists){
            return JsonResult.toFaild("命令已存在");
        }
        try {
            linuxRepository.save(lsc);
            return JsonResult.toSuccess();
        } catch (Exception e) {
            logger.error(e.getMessage());
            return JsonResult.toFaild(String.format("保存失败：%s",e.getMessage()));
        }
    }

    @RequestMapping("linuxCmdQuery")
    @ResponseBody
    public String toQueryCmd(@RequestParam(defaultValue = "0") int curPage, int pagesize, String keyword){
        String json = null;
        if(StringUtils.isEmpty(keyword)){
            //List<LinuxShellCmd> objList = linuxRepository.findAll();
            Sort sort = new Sort(Sort.Direction.ASC,"key");
            Page<LinuxShellCmd> p = linuxRepository.findAll(PageRequest.of(curPage,pagesize,sort));
            PageJson<LinuxShellCmd> pj = new PageJson();
            pj.setTotal(p.getTotalElements());
            pj.setData(p.getContent());
            json = JSON.toJSONString(pj);
        }else{
            Sort sort = new Sort(Sort.Direction.ASC,"key");
            //List<LinuxShellCmd> inList = linuxRepository.findByCmdContaining(keyword,);
            Page<LinuxShellCmd> p = null;
            try {
                p = linuxRepository.findAll(new Specification<LinuxShellCmd>() {
                    @Override
                    public Predicate toPredicate(Root<LinuxShellCmd> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                        List<Predicate> predicate = new ArrayList<>();
                        Predicate p1 = criteriaBuilder.like(root.get("key").as(String.class), "%" + keyword + "%");
                        Predicate p2 = criteriaBuilder.like(root.get("cmdDesc").as(String.class), "%" + keyword + "%");
                        predicate.add(criteriaBuilder.or(p1,p2));
                        Predicate[] pre = new Predicate[predicate.size()];
                        return criteriaQuery.where(predicate.toArray(pre)).getRestriction();
                    }
                }, PageRequest.of(curPage,pagesize,sort));
            } catch (Exception e) {
                e.printStackTrace();

            }
            PageJson<LinuxShellCmd> pj = new PageJson();
            pj.setTotal(p.getTotalElements());
            pj.setData(p.getContent());
            json = JSON.toJSONString(pj);
        }
        return json;
    }

    @RequestMapping("linuxCmdDel")
    @ResponseBody
    @Transactional
    public String linuxDel(String key){
        Integer b = linuxRepository.deleteLinuxShellCmdByKey(key);
        if(b>=1)
            return JsonResult.toSuccess();
        return JsonResult.toFaild();
    }

    @RequestMapping("linuxCmdUpdate")
    @ResponseBody
    public String linuxCmdUpdate(LinuxShellCmd lsc){
        try {
            linuxRepository.saveAndFlush(lsc);
            return JsonResult.toSuccess();
        } catch (Exception e) {
            return JsonResult.toFaild("更新失败！");
        }
    }
    /*
    //读取文件加载
    @RequestMapping("linuxCmdAdd")
    @ResponseBody
    public String toAddCmd(LinuxShellCmd lsc){
        List<LinuxShellCmd> objList = CacheManage.cache.get(CacheManage.LINUX_SHELL_CMD);
        boolean exists = false;
        for(LinuxShellCmd l : objList){
            exists = l.getKey().equals(lsc.getKey());
            if(exists) break;
        }
        if(exists){
            return JsonResult.toFaild("命令已存在");
        }
        objList.add(lsc);
        String contentCover = JSON.toJSONString(objList);
        String path = this.getClass().getResource("/").getPath();
        if(FileUtil.writeTo(new File(path+CacheManage.LINUX_SHELL_CMD_PATH),contentCover,false)){
            return JsonResult.toSuccess();
        }else{
            return JsonResult.toFaild();
        }
    }*/


   /*
    //从读取文件中获取数据
    @RequestMapping("linuxCmdQuery")
    @ResponseBody
    public String toQueryCmd(String keyword){
        String json = null;
        if(keyword==null){
            List<LinuxShellCmd> objList = CacheManage.cache.get(CacheManage.LINUX_SHELL_CMD);
            json = JSON.toJSONString(objList);
        }else{
            List<LinuxShellCmd> objList = CacheManage.cache.get(CacheManage.LINUX_SHELL_CMD);
            List<LinuxShellCmd> inList = new ArrayList<LinuxShellCmd>(10);
            for(int i=0;i<objList.size();i++){
                LinuxShellCmd lsc = objList.get(i);
                if(lsc.getCmd().contains(keyword)||lsc.getCmdDesc().contains(keyword)){
                    inList.add(lsc);
                }
            }
            json = JSON.toJSONString(inList);
        }
        return json;
    }*/
}
